#encoding: UTF-8
import os , json , types , re , uuid , time
import tornado.web
import Mgr

from handlers.baseHandler import BaseHandler
from handlers.gameDecorator import post_api_chk

from data.accountData import * 
from data.userData import * 



'''{
	msg_register_user 		--注册账号
    req-->>{
        tag = [tagname]%
        base={...},
        body={
           	name =  "",
           	pwd  = ""
        }
    }

    rep<<--{
        r    = svrstatu,
        err  = r!=0 then '',
        data = {
            ret = 0  	   --[0正常|1已注册]
        }

    }
}
'''

'''{
	msg_login 				--登录账号
    req-->>{
        tag = [tagname]%
        base={...},
        body={
           	name =  "",
           	pwd  = ""
        }
    }

    rep<<--{
        r    = svrstatu,
        err  = r!=0 then '',
        data = {
            ret = 0  	   --[0正常|1无用户|2密码错误]
        }
    }
}
'''

class accountHandler(BaseHandler):
	
	#chk has been registered? return :bool , userinfo
	def _chk_Registered(self , name):
		ret = accountData.find_by_name(name)
		if ret:
			return ret
	#chk login sucsss? return : bool , userinfo
	def _chk_Logined(self , name , pwd):
		ret = accountData.find_by_namepwd(name , pwd)
		if ret:
			return ret 
	def __crt_newaccount(self , name , pwd , ip):
		data = accountData.new(name , pwd , ip)
		return data

	def __get_usr(self , uid):
		print ("getuser")

	@post_api_chk
	def post(self , ret , apiname , rcv_dict , apinameold = ""):
		if not ret:
			func = self.__getattribute__(apiname)
			baseinfo = rcv_dict["base"]
			bodyinfo = rcv_dict["body"]
			if apiname == "msg_register_user":
				ret = func(bodyinfo["name"], bodyinfo["pwd"], self.request.remote_ip)
			elif apiname == "msg_login":
				ret = func(bodyinfo["name"] ,bodyinfo["pwd"], self.request.remote_ip)
		self.write(ret)
#=========================================
	def msg_register_user(self , name , pwd , ip):
		ret = None
		repdic = dict(
			ret = None
			)
		account = self._chk_Registered(name)
		if account:
			ret = 1	
		else:
			#create new account 
			new_account = self.__crt_newaccount(name , pwd , ip)
			accountData.insert_account(new_account)
			ret = 0

			logging.info("register one new usr--->>uid-%s|name-%s|pwd-%s|" % (uid , name , pwd))
		repdic["ret"] = ret
		return incExcept.raiseRet(repdic)
	def msg_login(self , name , inputpwd , ip):
		ret = 1  #默认是无用户
		repdic = dict(
			ret = None,
			Gdata = dict()
			)
		account = self._chk_Registered(name)
		if account:
			if account["pwd"] == inputpwd:
				ret = 0   #验证成功
			else: 
				ret = 2   #密码错误
		repdic["ret"] = ret 
		if ret == 0:
			repdic["Gdata"] = Mgr.entryGame(account)
		
		return incExcept.raiseRet(repdic)
	
	# def msg_newname(self, name):
	# 	if account
